/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.indexdatasource.service.impl;

import com.pingan.haofang.framework.common.functional.lang.control.base.Enums;
import com.pingan.haofang.gov.sm.account.common.UserThreadContext;
import com.pingan.haofang.searchcloud.common.constants.QueryOptimizeEnum;
import com.pingan.haofang.searchcloud.common.domain.BaseDomain;
import com.pingan.haofang.searchcloud.common.exception.FieldException;
import com.pingan.haofang.searchcloud.common.exception.FieldExceptionItem;
import com.pingan.haofang.searchcloud.common.exception.NotFoundException;
import com.pingan.haofang.searchcloud.index.constants.IndexConstants;
import com.pingan.haofang.searchcloud.index.constants.IndexDataSourceType;
import com.pingan.haofang.searchcloud.index.constants.IndexDatasourceStatus;
import com.pingan.haofang.searchcloud.index.dao.IndexDao;
import com.pingan.haofang.searchcloud.index.domain.Index;
import com.pingan.haofang.searchcloud.index.dto.IndexInfoQueryResult;
import com.pingan.haofang.searchcloud.index.dto.IndexQueryResult;
import com.pingan.haofang.searchcloud.index.service.IndexService;
import com.pingan.haofang.searchcloud.indexdatasource.dao.IndexDatasourceBuildDao;
import com.pingan.haofang.searchcloud.indexdatasource.dao.IndexDatasourceDao;
import com.pingan.haofang.searchcloud.indexdatasource.dao.IndexDatasourceRpcDao;
import com.pingan.haofang.searchcloud.indexdatasource.domain.IndexDatasource;
import com.pingan.haofang.searchcloud.indexdatasource.domain.IndexDatasourceBuild;
import com.pingan.haofang.searchcloud.indexdatasource.domain.IndexDatasourceRpc;
import com.pingan.haofang.searchcloud.indexdatasource.dto.DatasourceCacheKeyDto;
import com.pingan.haofang.searchcloud.indexdatasource.dto.IndexDatasourceBuildDTO;
import com.pingan.haofang.searchcloud.indexdatasource.dto.IndexDatasourceDTO;
import com.pingan.haofang.searchcloud.indexdatasource.dto.RpcIndexDataSourceDTO;
import com.pingan.haofang.searchcloud.indexdatasource.service.ImportDatasourceFacadeService;
import com.pingan.haofang.searchcloud.indexdatasource.service.IndexDatasourceService;
import com.pingan.haofang.searchcloud.metadata.dao.MetadataDao;
import com.pingan.haofang.searchcloud.metadata.dao.MetadataFieldDao;
import com.pingan.haofang.searchcloud.metadata.domain.Metadata;
import com.pingan.haofang.searchcloud.metadata.domain.MetadataField;
import com.pingan.haofang.searchcloud.quartz.service.IndexBuildScheduleTaskService;
import com.pingan.haofang.searchcloud.quartz.service.ScheduleTaskManager;
import com.pingan.haofang.searchcloud.user.dto.SearchUserDto;
import com.pingan.haofang.searchcloud.user.service.SearchUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 索引构建设置
 *
 * @author zhangbi617
 * @date 04/05/2017
 */
@Service
public class IndexDatasourceServiceImpl implements IndexDatasourceService {

    @Autowired
    private IndexDatasourceDao indexDatasourceDao;

    @Autowired
    private ImportDatasourceFacadeService importDatasourceFacadeService;

    @Autowired
    private IndexDatasourceRpcDao indexDatasourceRpcDao;

    @Autowired
    private IndexService indexService;

    @Autowired
    private IndexDatasourceBuildDao indexDatasourceBuildDao;

    @Autowired
    private SearchUserService searchUserService;

    @Autowired
    private IndexDao indexDao;

    @Autowired
    IndexBuildScheduleTaskService indexBuildScheduleTaskService;

    @Autowired
    private MetadataDao metadataDao;

    @Autowired
    private MetadataFieldDao metadataFieldDao;

    @Autowired
    private ScheduleTaskManager scheduleTaskManager;

    @Override
    public IndexDatasourceDTO getById(Long id) {
        Objects.requireNonNull(id, "id can not null");
        IndexDatasource indexDatasource = indexDatasourceDao.findOne(id);
        if (null == indexDatasource) {
            return null;
        }
        IndexDatasourceDTO dto = this.transfer(indexDatasource);
        SearchUserDto searchUserDto = searchUserService.getUserById(indexDatasource.getCreateBy());
        dto.setCreateByName(searchUserDto == null ? "" : searchUserDto.getUserName());
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createDatasource(IndexDatasourceDTO indexDatasourceDTO) {
        Objects.requireNonNull(indexDatasourceDTO, "indexDatasourceDTO can not null");
        Long indexId = indexDatasourceDTO.getIndexId();
        Objects.requireNonNull(indexId, "indexDatasourceDTO.indexId can not null");
        String name = indexDatasourceDTO.getName();
        Objects.requireNonNull(name, "indexDatasourceDTO.name can not null");

        if(null != indexDatasourceDTO.getFullDatasourceRpc() && null != indexDatasourceDTO.getFullDatasourceRpc().getIndexField()){
            //处理""情况
            if(StringUtils.isEmpty(indexDatasourceDTO.getFullDatasourceRpc().getIndexField())){
                indexDatasourceDTO.getFullDatasourceRpc().setIndexField(null);
            }
            if((null == indexDatasourceDTO.getFullDatasourceRpc().getQueryOptimize() || !indexDatasourceDTO.getFullDatasourceRpc().getQueryOptimize().equals(QueryOptimizeEnum.ENABLE.code())) && StringUtils.isNotEmpty(indexDatasourceDTO.getFullDatasourceRpc().getIndexField())){
                throw new FieldException("please check out the lastMaxId when filled in the optimize field");
            }
        }

        if (checkNameExist(indexId, name)) {

            throw new FieldException(
                    new FieldExceptionItem("name",
                            "indexDatasource.name.exist", indexDatasourceDTO.getName()));
        }

        if (!checkIndexFiledExist(indexDatasourceDTO)) {

            throw new FieldException(
                    "unKnow column "+ indexDatasourceDTO.getFullDatasourceRpc().getIndexField()+",please check the schema field");
        }

        final Date now = new Date();

        IndexDatasource indexDatasource = dto2IndexDatasource(indexDatasourceDTO);
        indexDatasource.setStatus(IndexDatasourceStatus.NORMAL.getId());
        indexDatasource.setUpdateTime(now);

        RpcIndexDataSourceDTO fullDTO = indexDatasourceDTO.getFullDatasourceRpc();
        if (null != fullDTO) {
            IndexDatasourceRpc fullRpc = dto2IndexDatasourceRpc(fullDTO);
            if (fullRpc != null && fullRpc.getQueryOptimize() == null) {
                fullRpc.setQueryOptimize(QueryOptimizeEnum.DISABLE.code());
            }

            if(fullRpc.getThreadNum() == null){
                fullRpc.setThreadNum(IndexConstants.DEFAULT_THREAD_NUM);
            }
            fullRpc = indexDatasourceRpcDao.saveAndFlush(fullRpc);
            indexDatasource.setFullDatasourceId(fullRpc.getId());
        }

        RpcIndexDataSourceDTO incDTO = indexDatasourceDTO.getIncDatasourceRpc();
        if (null != incDTO) {
            IndexDatasourceRpc incrRpc = dto2IndexDatasourceRpc(incDTO);
            if (incrRpc != null && incrRpc.getQueryOptimize() == null) {
                incrRpc.setQueryOptimize(QueryOptimizeEnum.DISABLE.code());
                incrRpc.setThreadNum(IndexConstants.DEFAULT_THREAD_NUM);
            }
            incrRpc.setBufferStatus(0);
            incrRpc = indexDatasourceRpcDao.saveAndFlush(incrRpc);
            indexDatasource.setIncDatasourceId(incrRpc.getId());
        }

        indexDatasourceDao.saveAndFlush(indexDatasource);


        return true;
    }

    private boolean checkNameExist(Long indexId, String dataSourceName) {
        List<IndexDatasourceDTO> dtos = this.findDatasource(indexId, dataSourceName);
        return CollectionUtils.isNotEmpty(dtos);
    }

    private boolean checkIndexFiledExist(IndexDatasourceDTO indexDatasourceDTO) {
        boolean result = false;
        if(null == indexDatasourceDTO.getFullDatasourceRpc() || StringUtils.isEmpty(indexDatasourceDTO.getFullDatasourceRpc().getIndexField())){
            return !result;
        }

        //注解已经验证过metas是否存在
        List<Metadata> metas = metadataDao.findFirst1ByIndexIdOrderByConfigVersionDesc(indexDatasourceDTO.getIndexId());

        List<MetadataField> metadataFields =  metadataFieldDao.findByMetaId(metas.get(0).getId());
        if (CollectionUtils.isEmpty(metas)){
            throw new NotFoundException("meta data field not found");
        }
        //有这个字段即可
        return metadataFields.stream().map(MetadataField::getFieldName).collect(Collectors.toList()).contains(indexDatasourceDTO.getFullDatasourceRpc().getIndexField());
    }

    private IndexDatasourceRpc dto2IndexDatasourceRpc(RpcIndexDataSourceDTO dto) {
        IndexDatasourceRpc rpc = new IndexDatasourceRpc();


        rpc.setRpcUrl(dto.getRpcUrl());
        rpc.setRpcMethod(dto.getRpcMethod());
        rpc.setImportCron(dto.getCron());
        rpc.setIndexField(dto.getIndexField());
        rpc.setImportPageize(dto.getPageSize());
        rpc.setImportStartPage(dto.getStartPage());
        rpc.setStatus(IndexDatasourceStatus.NORMAL.getId());
        rpc.setBufferStatus(dto.getBufferStatus());
        rpc.setBufferSize(dto.getBufferSize() == null ? 0 : dto.getBufferSize());
        rpc.setMaxWaitTime(dto.getMaxWaitTime() == null ? 0 : dto.getMaxWaitTime());
        // 线程数量
        rpc.setThreadNum(dto.getThreadNum());
        // 是否查询优化
        rpc.setQueryOptimize(dto.getQueryOptimize());
        return rpc;

    }

    private IndexDatasource dto2IndexDatasource(IndexDatasourceDTO dto) {
        IndexDatasource indexDatasource = new IndexDatasource();
        indexDatasource.setName(dto.getName());
        indexDatasource.setIndexId(dto.getIndexId());

        RpcIndexDataSourceDTO fullDTO = dto.getFullDatasourceRpc();
        indexDatasource.setFullDatasourceType(dto.getFullDatasourceType());
        indexDatasource.setFullDatasourceId(-1L);
        if (null != fullDTO) {
            indexDatasource.setFullDatasourceId(fullDTO.getId());
        }

        RpcIndexDataSourceDTO incDTO = dto.getIncDatasourceRpc();

        indexDatasource.setIncDatasourceType(dto.getIncDatasourceType());
        indexDatasource.setIncDatasourceId(-1L);
        if (null != incDTO) {
            indexDatasource.setIncDatasourceId(incDTO.getId());
        }

        return indexDatasource;
    }

    @Override
    @Transactional
    public boolean updateDatasource(IndexDatasourceDTO dto) throws SchedulerException {
        Objects.requireNonNull(dto, "indexDatasourceDTO can not be null");
        Objects.requireNonNull(dto.getId(), "indexDatasourceDTO.id can not be null");
        DatasourceCacheKeyDto keyDto = this.deleteDatasource(dto.getId());

        boolean isCreatSucess = this.createDatasource(dto);
        if (!isCreatSucess) {
            throw new RuntimeException("createDatasource has error");
        }
        return true;
    }


    @Override
    @Transactional
    public DatasourceCacheKeyDto deleteDatasource(Long id) throws SchedulerException {
        IndexDatasource indexDatasource = indexDatasourceDao.findOne(id);
        if (null == indexDatasource) {
            throw new NotFoundException("indexDatasource not found");
        }

        Long opId = UserThreadContext.getSessionVisitor().getAccountId();
        Long incId = indexDatasource.getIncDatasourceId();
        if (null != incId) {
            IndexDataSourceType incIndexBuildType = Enums.findValue(indexDatasource.getIncDatasourceType(),
                    IndexDataSourceType.class);
            importDatasourceFacadeService.updateStatus(incId, IndexDatasourceStatus.DISABLE.getId(), opId,
                    incIndexBuildType);
        }

        Long fullId = indexDatasource.getFullDatasourceId();
        if (null != fullId) {
            IndexDataSourceType fullIndexBuildType = Enums.findValue(indexDatasource.getFullDatasourceType(),
                    IndexDataSourceType.class);
            importDatasourceFacadeService.updateStatus(fullId, IndexDatasourceStatus.DISABLE.getId(), opId,
                    fullIndexBuildType);
        }

        indexDatasourceDao.updateStatus(id, IndexDatasourceStatus.DISABLE.getId(), opId);

        //查索引名称名称构建清除缓存key
        Index index = indexDao.findOne(indexDatasource.getIndexId());
        if (null == index) {
            throw new NotFoundException("index not found");
        }
        if (StringUtils.isNotBlank(index.getIndexName()) && StringUtils.isNotBlank(indexDatasource.getName())) {
            return new DatasourceCacheKeyDto(index.getId(), index.getIndexName(), indexDatasource.getName());
        }

        return null;
    }

    @Override
    @CacheEvict(value = "searchcloud_cache_datasource", key = "#keyDto.indexName+'_'+#keyDto.datasourceName")
    public void datasourceCacheEvict(DatasourceCacheKeyDto keyDto) {
        //清缓存用 无内容
    }


    private IndexDatasourceDTO transfer(IndexDatasource indexDatasource) {
        if (indexDatasource == null) {
            return null;
        }

        // 全量数据拼接
        BaseDomain fullDatasouce = null;
        IndexDataSourceType fullIndexBuildType = Enums.findValue(indexDatasource.getFullDatasourceType(),
                IndexDataSourceType.class);
        switch (fullIndexBuildType) {
            case JSON_RPC:
                fullDatasouce = indexDatasourceRpcDao.findByIdAndStatus(indexDatasource.getFullDatasourceId(),
                        IndexDatasourceStatus.NORMAL.getId());
                break;
            default:
                break;
        }

        // 增量数据拼接
        BaseDomain incDatasouce = null;
        IndexDataSourceType incIndexBuildType = Enums.findValue(indexDatasource.getIncDatasourceType(),
                IndexDataSourceType.class);
        switch (incIndexBuildType) {
            case JSON_RPC:
                incDatasouce = indexDatasourceRpcDao.findByIdAndStatus(indexDatasource.getIncDatasourceId(),
                        IndexDatasourceStatus.NORMAL.getId());
                break;
            default:
                break;
        }

        return transfer(indexDatasource, fullDatasouce, incDatasouce);
    }

    /**
     * 数据转换
     *
     * @param indexDatasource 索引数据源
     * @param fullDataSource  全量数据源
     * @param incDataSource   增量数据源
     * @return
     */
    private IndexDatasourceDTO transfer(IndexDatasource indexDatasource,
                                        BaseDomain fullDataSource, BaseDomain incDataSource) {
        if (indexDatasource == null) {
            return null;
        }
        IndexDatasourceDTO indexDatasourceDTO = transferBasic(indexDatasource);

        // 全量数据拼接
        IndexDataSourceType fullIndexBuildType = Enums.findValue(indexDatasourceDTO.getFullDatasourceType(),
                IndexDataSourceType.class);
        switch (fullIndexBuildType) {
            case JSON_RPC:
                indexDatasourceDTO.setFullDatasourceRpc(transformRpcIndexBuild((IndexDatasourceRpc) fullDataSource));
                break;
            default:
                break;
        }

        // 增量数据拼接
        if (indexDatasourceDTO.getIncDatasourceType() != null) {
            IndexDataSourceType incIndexBuildType = Enums.findValue(indexDatasourceDTO.getIncDatasourceType(),
                    IndexDataSourceType.class);
            switch (incIndexBuildType) {
                case JSON_RPC:
                    indexDatasourceDTO.setIncDatasourceRpc(transformRpcIndexBuild((IndexDatasourceRpc) incDataSource));
                    break;
                default:
                    break;
            }
        }

        return indexDatasourceDTO;
    }

    private IndexDatasourceDTO transferBasic(IndexDatasource indexDatasource) {
        IndexDatasourceDTO indexDatasourceDTO = new IndexDatasourceDTO();
        indexDatasourceDTO.setFullDatasourceType(indexDatasource.getFullDatasourceType());
        indexDatasourceDTO.setIncDatasourceType(indexDatasource.getIncDatasourceType());
        indexDatasourceDTO.setId(indexDatasource.getId());
        indexDatasourceDTO.setName(indexDatasource.getName());
        indexDatasourceDTO.setIndexId(indexDatasource.getIndexId());
        return indexDatasourceDTO;
    }

    /**
     * indexImportRpc转换为RpcIndexBuildDTO
     *
     * @param indexDatasourceRpc
     * @return
     */
    private RpcIndexDataSourceDTO transformRpcIndexBuild(IndexDatasourceRpc indexDatasourceRpc) {
        RpcIndexDataSourceDTO dto = new RpcIndexDataSourceDTO();
        dto.setId(indexDatasourceRpc.getId());
        dto.setCron(indexDatasourceRpc.getImportCron());
        dto.setPageSize(indexDatasourceRpc.getImportPageize());
        dto.setStartPage(indexDatasourceRpc.getImportStartPage());
        dto.setRpcUrl(indexDatasourceRpc.getRpcUrl());
        dto.setRpcMethod(indexDatasourceRpc.getRpcMethod());
        dto.setBufferStatus(indexDatasourceRpc.getBufferStatus());
        dto.setBufferSize(indexDatasourceRpc.getBufferSize());
        dto.setMaxWaitTime(indexDatasourceRpc.getMaxWaitTime());
        // 线程数量
        dto.setThreadNum(indexDatasourceRpc.getThreadNum());
        // 是否查询优化
        dto.setQueryOptimize(indexDatasourceRpc.getQueryOptimize());
        // 优化查询字段
        dto.setIndexField(indexDatasourceRpc.getIndexField());
        //放入增量 cron
        dto.setCron(indexDatasourceRpc.getImportCron());
        return dto;
    }

    @Override
    public List<IndexDatasourceDTO> getByIndexId(Long indexId) {
        Objects.requireNonNull(indexId, "indexId can not null");
        List<IndexDatasource> indexDatasources = indexDatasourceDao.findByIndexId(indexId,
                IndexDatasourceStatus.NORMAL.getId());
        if (CollectionUtils.isEmpty(indexDatasources)) {
            return Collections.emptyList();
        }

        Set<Long> createBys = indexDatasources.stream().map(IndexDatasource::getCreateBy).collect(Collectors.toSet());
        Map<Long, SearchUserDto> searchUserDtoMap = searchUserService.getUserMapByIds(createBys);

        List<IndexDatasourceDTO> dtoList = new ArrayList<>();
        for (IndexDatasource indexDatasource : indexDatasources) {
            IndexDatasourceDTO dto = transfer(indexDatasource);
            SearchUserDto searchUserDto = searchUserDtoMap.get(indexDatasource.getCreateBy());
            if (searchUserDto != null) {
                dto.setCreateByName(searchUserDto.getUserName());
            }
            dtoList.add(dto);
        }

        return dtoList;
    }

    @Override
    @Cacheable(value = "searchcloud_cache_datasource", key = "#indexName+'_'+#datasourceName")
    public IndexDatasourceDTO findDatasource(String projectCode, String indexName, String datasourceName) {
        IndexInfoQueryResult result = indexService.queryByIndexNameOfStorage(indexName);
        if (null == result) {
            Collections.emptyList();
        }
        IndexQueryResult index = result.getBasicInfo();
        List<IndexDatasourceDTO> dtoList = this.findDatasource(index.getId(), datasourceName);
        if (CollectionUtils.isEmpty(dtoList)) {
            return null;
        }
        if (dtoList.size() > 1) {
            throw new RuntimeException(String.format("project[%s] index[%s] has more one datasource[%s] ", projectCode,
                    indexName, datasourceName));
        }
        return dtoList.get(0);
    }


    @Override
    public List<IndexDatasourceDTO> findDatasource(Long indexId, String datasourceName) {
        List<IndexDatasource> indexDatasources = indexDatasourceDao.findByIndexIdAndName(indexId, datasourceName,
                IndexDatasourceStatus.NORMAL.getId());

        if (CollectionUtils.isEmpty(indexDatasources)) {
            return Collections.emptyList();
        }

        List<IndexDatasourceDTO> dtoList = new ArrayList<IndexDatasourceDTO>();
        for (IndexDatasource indexDatasource : indexDatasources) {
            IndexDatasourceDTO dto = transfer(indexDatasource);
            dtoList.add(dto);
        }

        return dtoList;
    }

    @Override
    public List<IndexDatasourceDTO> findDatasource(String projectCode, String indexName) {
        IndexInfoQueryResult result = indexService.queryByIndexNameOfStorage(indexName);
        if (null == result) {
            Collections.emptyList();
        }
        IndexQueryResult index = result.getBasicInfo();

        return getByIndexId(index.getId());
    }

    @Override
    public List<IndexDatasourceDTO> findDatasourceByIndexIds(Collection<Long> indexIdList) {

        List<IndexDatasource> indexDatasources = indexDatasourceDao.findByIndexIds(indexIdList,
                IndexDatasourceStatus.NORMAL.getId());

        if (CollectionUtils.isEmpty(indexDatasources)) {
            return Collections.emptyList();
        }

        Set<Long> rpcDatasourceIdList = new HashSet<>();
        for (IndexDatasource indexDatasource : indexDatasources) {
            IndexDataSourceType fullIndexBuildType = Enums.findValue(indexDatasource.getFullDatasourceType(),
                    IndexDataSourceType.class);
            switch (fullIndexBuildType) {
                case JSON_RPC:
                    rpcDatasourceIdList.add(indexDatasource.getFullDatasourceId());
                    break;
                default:
                    break;
            }

            if (indexDatasource.getIncDatasourceType() != null) {
                IndexDataSourceType incIndexBuildType = Enums.findValue(indexDatasource.getIncDatasourceType(),
                        IndexDataSourceType.class);
                switch (incIndexBuildType) {
                    case JSON_RPC:
                        rpcDatasourceIdList.add(indexDatasource.getIncDatasourceId());
                        break;
                    default:
                        break;
                }
            }

        }

        List<IndexDatasourceRpc> indexDatasourceRpcList = (List<IndexDatasourceRpc>) importDatasourceFacadeService
                .findByIdsAndStatus(rpcDatasourceIdList, IndexDatasourceStatus.NORMAL, IndexDataSourceType.JSON_RPC);
        indexDatasourceRpcList = (indexDatasourceRpcList == null) ? Collections.emptyList() : indexDatasourceRpcList;
        Map<Long, IndexDatasourceRpc> indexDatasourceRpcMap = indexDatasourceRpcList.stream()
                .collect(Collectors.toMap(IndexDatasourceRpc::getId, (p) -> p));

        List<IndexDatasourceDTO> indexDatasourceDTOList = new ArrayList<>();
        for (IndexDatasource indexDatasource : indexDatasources) {
            IndexDatasourceDTO datasourceDTO = transfer(indexDatasource,
                    indexDatasourceRpcMap.get(indexDatasource.getFullDatasourceId()),
                    indexDatasourceRpcMap.get(indexDatasource.getIncDatasourceId()));
            indexDatasourceDTOList.add(datasourceDTO);
        }

        return indexDatasourceDTOList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDatasourceBuild(IndexDatasourceBuildDTO indexDatasourceBuildDTO) throws SchedulerException {
        Objects.requireNonNull(indexDatasourceBuildDTO);
        Objects.requireNonNull(indexDatasourceBuildDTO.getCron());
        Objects.requireNonNull(indexDatasourceBuildDTO.getIndexId());

        IndexDatasourceBuild indexDatasourceBuild =
                indexDatasourceBuildDao.findByIndexId(indexDatasourceBuildDTO.getIndexId());

        if (indexDatasourceBuild == null) {
            indexDatasourceBuild = new IndexDatasourceBuild();
            indexDatasourceBuild.setIndexId(indexDatasourceBuildDTO.getIndexId());
        }
        indexDatasourceBuild.setCron(indexDatasourceBuildDTO.getCron());
        indexDatasourceBuild.setIncCron(indexDatasourceBuildDTO.getIncCron());
        indexDatasourceBuildDao.saveAndFlush(indexDatasourceBuild);
        indexBuildScheduleTaskService.refresh(indexDatasourceBuildDTO.getIndexId());
        indexBuildScheduleTaskService.incScheduleRefresh(indexDatasourceBuildDTO.getIndexId());


    }

    @Override
    public IndexDatasourceBuildDTO getDatasourceBuild(Long indexId) {
        IndexDatasourceBuild indexDatasourceBuild = indexDatasourceBuildDao.findByIndexId(indexId);
        if (indexDatasourceBuild == null) {
            return null;
        }
        return transferToDTO(indexDatasourceBuild);
    }

    private IndexDatasourceBuildDTO transferToDTO(IndexDatasourceBuild indexDatasourceBuild) {
        IndexDatasourceBuildDTO indexDatasourceBuildDTO = new IndexDatasourceBuildDTO();
        indexDatasourceBuildDTO.setCron(indexDatasourceBuild.getCron());
        indexDatasourceBuildDTO.setId(indexDatasourceBuild.getId());
        indexDatasourceBuildDTO.setIndexId(indexDatasourceBuild.getIndexId());
        indexDatasourceBuildDTO.setIncCron(indexDatasourceBuild.getIncCron());
        return indexDatasourceBuildDTO;
    }

    @Override
    public List<IndexDatasourceBuildDTO> findDatasourceBuildByIndexIds(Set<Long> indexIds) {
        List<IndexDatasourceBuild> result = indexDatasourceBuildDao.findByIndexIdIn(indexIds);
        if (CollectionUtils.isEmpty(result)) {
            return Collections.emptyList();
        }

        List<IndexDatasourceBuildDTO> indexDatasourceBuildDTOList = new ArrayList<>();
        for (IndexDatasourceBuild po : result) {
            indexDatasourceBuildDTOList.add(transferToDTO(po));
        }
        return indexDatasourceBuildDTOList;
    }

    @Override
    public IndexDatasourceDTO findByIdSimple(Long datasourceId) {
        Objects.requireNonNull(datasourceId, "id can not null");
        IndexDatasource indexDatasource = indexDatasourceDao.findOne(datasourceId);
        if (null == indexDatasource) {
            return null;
        }
        return transferBasic(indexDatasource);
    }

}
